package documentation_logic

import (
	"context"
	"errors"
	"fmt"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListDocumentsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewListDocumentsLogic 查询所有知识库
func NewListDocumentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListDocumentsLogic {
	return &ListDocumentsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListDocumentsLogic) ListDocuments(req *types.ListDocumentsReq) (resp *types.ListDocumentsResp, err error) {

	if req.Page <= 0 || req.PageSize <= 0 {
		err = errors.New("invalid page or page size")
		l.Logger.Error(err)
		return &types.ListDocumentsResp{
			Code:    500,
			Message: err.Error(),
		}, nil
	}

	var documents []types.Document
	offset := (req.Page - 1) * req.PageSize
	query := fmt.Sprintf(`SELECT id, title, author, content, component, tags, content_summary, created_at, updated_at 
              FROM %s WHERE component = ? LIMIT ? OFFSET ?`, l.svcCtx.Config.Mysql.Tables.DocumentationKnowledge)
	err = l.svcCtx.Conn.QueryRowsCtx(l.ctx, &documents, query, req.Component, req.PageSize, offset)
	if err != nil {
		l.Logger.Error("Query failed", logx.Field("error", err))
		return nil, err
	}

	// 处理空结果
	if len(documents) == 0 {
		l.Logger.Info("No documents found")
		return &types.ListDocumentsResp{
			Code:    500,
			Message: "No documents found",
			Data:    []types.Document{},
		}, nil
	}

	return &types.ListDocumentsResp{
		Code:    200,
		Message: "success",
		Data:    documents,
	}, nil
}
